% Function:
%   convert data file to standard format
% Argument:
%   folder: folder of data files
%   base  : base time for input file
% Return:
%   r: aligned data
function r = cvrt(folder, base)
    if nargin ~= 2
        error('Usage: cvrt(folder, base)');
    end

    if ~exist(folder, 'dir')
        error(['folder ''', folder, '''do not exist']);
    end

    d = dir(fullfile(folder, 'ET*_Time.txt')); fTime = fullfile(folder, d(1).name);
    d = dir(fullfile(folder, 'ET*_Temp.txt')); fTemp = fullfile(folder, d(1).name);
    d = dir(fullfile(folder, '20181120090253tc18101202DT.txt')); fData = fullfile(folder, d(1).name);

    Time = load(fTime);
    Temp = load(fTemp);
    data = load(fData);

    % round time of data
    data(:, 1) = fix(data(:, 1)) + base;
    data(:, 8) = fix(data(:, 8) * 100);

    m = numel(Time);
    n = size(data, 1);

    % allocate memory
    r = zeros(m, 7);

    % align data as time sequence
    k = 1;
    s = 1;
    while data(1, 1) > Time(s)
        r(s, :) = data(1, 2:8);
        s       = s + 1;
    end
    for i = s : m
        while k <= n && data(k, 1) ~= Time(i)
            k = k + 1;
        end

        if k > n
            warning(['can not find time ', num2str(Time(i))]);
            r(i:end, :) = repmat(data(end, 2:8), m - i + 1, 1);
            break;
        end

        r(i, :) = data(k, 2:8);
    end

    % write results to files
    fid1 = fopen(fullfile(folder, '_Temp.txt'), 'w', 'n', 'UTF-8');
    fid2 = fopen(fullfile(folder, '_Comp.txt'), 'w', 'n', 'UTF-8');

    n = size(Temp, 2);

    for i = 1 : m
        % file: '_Temp.txt'
        for j = 1 : 6
            fprintf(fid1, '%.2f\t', r(i, j));
        end
        for j = 1 : n
            fprintf(fid1, '%.2f\t', Temp(i, j));
        end
        fprintf(fid1, '\r\n');

        % file: '_Comp.txt'
        fprintf(fid2, '%d\r\n', r(i, 7));
    end

    fclose(fid1);
    fclose(fid2);
end
